package com.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.test.bean.TextMeaasge;
import com.test.utils.WeiXinSignatureUtil;
import com.test.utils.WeiXinMsgUtil;

/**
 * 
 * @author 殷田
 *
 */
public class WeiXin extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	protected void doGet( HttpServletRequest request, HttpServletResponse response )
					throws ServletException, IOException
	{
		// 微信加密签名
		String signature = request.getParameter( "signature" );
		// 时间戳
		String timestamp = request.getParameter( "timestamp" );
		// 随机数
		String nonce = request.getParameter( "nonce" );
		// 随机字符串
		String echostr = request.getParameter( "echostr" );
		// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		if ( signature != null && WeiXinSignatureUtil.checkSignature( signature, timestamp, nonce ) )
		{
			try
			{
				PrintWriter print = response.getWriter();
				print.write( echostr );
				print.flush();
			}
			catch ( IOException e )
			{
				e.printStackTrace();
			}
		}
	}

	protected void doPost( HttpServletRequest request, HttpServletResponse response )
					throws ServletException, IOException
	{
		request.setCharacterEncoding( "utf-8" );
		response.setContentType( "text/xml;charset=utf-8" );
		try
		{
			Map< String, String > map = WeiXinMsgUtil.xmlToMap( request );
			String toUserName = map.get( "ToUserName" );
			String fromUserName = map.get( "FromUserName" );
			String msgType = map.get( "MsgType" );
			String content = map.get( "Content" );
			String message = null;
			if ( WeiXinMsgUtil.MESSAGE_TEXT.equals( msgType ) )
			{ // 对文本消息进行处理
				TextMeaasge text = new TextMeaasge();
				text.setFromUserName( toUserName ); // 发送和回复是反向的
				text.setToUserName( fromUserName );
				text.setMsgType( WeiXinMsgUtil.MESSAGE_TEXT );
				text.setCreateTime( new Date().getTime() + "" );
				text.setContent( "你好,已接收到内容: "+content );
				message = WeiXinMsgUtil.textMessageToXML( text );
			}
			PrintWriter out = response.getWriter();
			out.print( message );
			out.close();
		}
		catch ( Exception e )
		{
			e.printStackTrace();
		}
	}

}
